package com.gwm.starter.oss.controller;

import cn.hutool.core.util.StrUtil;
import com.gwm.starter.oss.service.GwmOssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ContentDisposition;
import org.springframework.http.MediaType;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
public class UniformController {

    @Resource
    private GwmOssService ossService;

    @GetMapping(value = "images/view/**")
    public void minioView1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pathStr = extractPathFromPattern(request);
        String bucketName = getBucketName(pathStr);
        String filePath = getFilePath(pathStr);
        try (InputStream inputStream = ossService.getInputStreamWithBucket(bucketName, filePath);
             OutputStream outputStream = response.getOutputStream()
        ) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        }
    }

    @GetMapping(value = "svg/view/**")
    public void minioView2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("image/svg+xml");
        String pathStr = extractPathFromPattern(request);
        String bucketName = getBucketName(pathStr);
        String filePath = getFilePath(pathStr);
        try (InputStream inputStream = ossService.getInputStreamWithBucket(bucketName, filePath);
             OutputStream outputStream = response.getOutputStream()
        ) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        }
    }

    @GetMapping(value = "/file/**")
    public void minioView3(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pathStr = extractPathFromPattern(request);
        String bucketName = getBucketName(pathStr);
        String filePath = getFilePath(pathStr);
        String fileName = getFileName(pathStr);

        response.reset();
        response.addHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);

        ContentDisposition disposition = ContentDisposition.builder("attachment").filename(fileName).build();
        response.addHeader("Content-Disposition", disposition.toString());

        try (InputStream inputStream = ossService.getInputStreamWithBucket(bucketName, filePath);
             OutputStream outputStream = response.getOutputStream()
        ) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        }
    }


    /**
     *  把指定URL后的字符串全部截断当成参数
     *  这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     * @param request req
     * @return res
     */
    private String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        log.info("path = {}", path);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        log.info("bestMatchPattern = {}", bestMatchPattern);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

    private String getBucketName(String pathStr) {
        Path path = Paths.get(pathStr);
        Path subpath = path.subpath(0, 1);
        return subpath.toString();
    }

    private String getFilePath(String pathStr) {
        String bucketName = getBucketName(pathStr);
        return pathStr.replaceFirst(bucketName + "/", "");
    }

    private String getFileName(String pathStr) {
        Path path = Paths.get(pathStr);
        return path.getFileName().toString();
    }

}
